<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="模块名称" prop="moduleName">
        <el-input v-model="formItem.moduleName" placeholder="请输入模块名称" />
      </el-form-item>
      <el-form-item label="模块编码" prop="moduleCode">
        <el-input v-model="formItem.moduleCode" placeholder="请输入模块编码" />
      </el-form-item>
      <el-form-item label="模板" prop="configTemplet">
        <el-input v-model="formItem.configTemplet" placeholder="请输入模板" />
      </el-form-item>
      <el-form-item label="是否自动增长" prop="autoIncrement">
        <el-radio v-model="formItem.autoIncrement" title="以模板SN000为例，生成的序列号为SN1、SN2、SN3..." :label="true">是</el-radio>
        <el-radio v-model="formItem.autoIncrement" title="以模板SN000为例，生成的序列号为SN001、SN002、SN003..." :label="false">否</el-radio>
      </el-form-item>
      <el-form-item label="预生成数量" prop="preMaxNum">
        <el-input-number v-model="formItem.preMaxNum" :precision="0" :step="1" :min="1" :max="1000000000" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  create,
  update,
  detail
} from '@neu/dcam-ui/api/serialNumber'

// 定义一个表单原始项
const formItem = {
  moduleName: '',
  moduleCode: '',
  configTemplet: '',
  autoIncrement: false,
  maxSerial: '',
  preMaxNum: ''
}
export default {
  name: 'SerailNumberEditForm',
  components: {},
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        moduleName: [{ required: true, message: '模块名称不能为空', trigger: 'blur' }],
        moduleCode: [{ required: true, message: '模块编码不能为空', trigger: 'blur' }],
        configTemplet: [{ required: true, message: '模板不能为空', trigger: 'blur' }],
        autoIncrement: [{ required: true, message: '是否自动增长不能为空', trigger: 'blur' }],
        preMaxNum: [{ required: true, message: '预生成数量不能为空', trigger: 'blur' }]
      },
      modal: true
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = {
            ...response.data
          }
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
    }
  }
}
</script>
